<template>
  <div class="menu">
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" v-auth="'org:add'"> 新增机构 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="[
            {
              onClick: handleLook.bind(null, record),
              label: '查看',
            },
            {
              onClick: handleEdit.bind(null, record),
              label: '编辑',
              auth: 'org:edit'
            },
            {
              color: 'error',
              onClick: handleDelete.bind(null, record),
              label: '删除',
              auth: 'org:delete'
            },
          ]" />
        </template>
      </template>
    </BasicTable>
    <MenuModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table';

import { useModal } from '@/components/Modal';
import MenuModal from './Modal.vue';

import { columns, searchFormSchema } from './index.data';

import { useMessage } from '@/hooks/web/useMessage';

import * as api from '@/api/system/org';

defineOptions({ name: 'MenuManagement' });

const { createConfirm } = useMessage();
const [registerModal, { openModal }] = useModal();
const [registerTable, { reload }] = useTable({
  api: api.list,
  columns,
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
  },
  isTreeTable: true,
  pagination: false,
  striped: false,
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  canResize: false,
  fetchSetting: {
    // 传给后台的当前页字段
    pageField: 'pageIndex',
    // 传给后台的每页显示多少条的字段
    sizeField: 'pageSize',
    // 接口返回表格数据的字段
    listField: 'data.entities',
    // 接口返回表格总数的字段
    totalField: 'data.totalCount',
  },
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
    fixed: 'right',
  },
});

function handleCreate() {
  openModal(true, {
    isUpdate: false,
    isLook: false,
  });
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    isLook: false,
  });
}
function handleLook(record: Recordable) {
  openModal(
    true,
    {
      record,
      isUpdate: true,
      isLook: true,
    },
    true,
  );
}

function handleDelete(record: Recordable) {
  createConfirm({
    title: '删除机构',
    content: '确定要删除吗？删除后不可恢复',
    iconType: 'warning',
    onOk: async () => {
      await api.del(record.id);
      reload();
    },
  });
}

function handleSuccess() {
  reload();
}

function onFetchSuccess() {
  // 演示默认展开所有表项
}
</script>
